package org.jeecg.modules.nikeProject.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.nikeProject.ProjectCodeUtils;
import org.jeecg.modules.nikeProject.entity.*;
import org.jeecg.modules.nikeProject.entity.vo.CheckInfoVO;
import org.jeecg.modules.nikeProject.entity.vo.OssFileVO;
import org.jeecg.modules.nikeProject.entity.vo.PersonalInfoVO;
import org.jeecg.modules.nikeProject.entity.vo.PublicInfoVO;
import org.jeecg.modules.nikeProject.mapper.*;
import org.jeecg.modules.nikeProject.service.ISportsPersonalInfoService;
import org.jeecg.modules.nikeProject.service.ISportsProjectFileService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.util.HttpUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Description: 案例评审-个人基本信息
 * @Author: jeecg-boot
 * @Date:   2024-12-05
 * @Version: V1.0
 */
@Slf4j
@Service
public class SportsPersonalInfoServiceImpl extends ServiceImpl<SportsPersonalInfoMapper, SportsPersonalInfo> implements ISportsPersonalInfoService {

    @Autowired
    private SportsProjectMapper sportsProjectMapper;
    
    @Autowired
    private SportsPersonalInfoMapper sportsPersonalInfoMapper;

    @Autowired
    private SportsPersonalEduMapper sportsPersonalEduMapper;

    @Autowired
    private SportsPersonalWorkExperienceMapper sportsPersonalWorkExperienceMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserVerifyLogMapper sysUserVerifyLogMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISportsProjectFileService sportsProjectFileService;

    public boolean getUserProject(String roleType, String username){
        Calendar calendar = Calendar.getInstance();
        LambdaQueryWrapper<SportsProject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SportsProject::getIzActive, CommonConstant.COMMON_STATUS_N);
        queryWrapper.eq(SportsProject::getRoleType, roleType);
        queryWrapper.eq(SportsProject::getYear, calendar.get(Calendar.YEAR));
        queryWrapper.eq(SportsProject::getCreateBy, username);
        Long i =  sportsProjectMapper.selectCount(queryWrapper);
        if (i > 1) {
            return false;
        }
        return true;
    }

    /**
     * 新增个人信息
     * @param personalInfoVO
     * @param username
     * @return
     */
    @Override
    @Transactional
    public Result<?> savePersonalInfo(PersonalInfoVO personalInfoVO, String username) {
        Map<String, Object> map = new HashMap<>();
        SysUser user = sysUserMapper.getUserByPhone(username);
        if (null == user) {
            user = sysUserMapper.getUserByName(username);
            if (null == user) {
                return Result.error("当前用户不存在！");
            }
        }
        String projectId = "";
        //通过projectId判断是新增还是修改，如果修改先将对应的数据删除掉，再做新增操作
        if (null != personalInfoVO.getProjectId()) {
            //从传入的数据里边获取projectId
            projectId = personalInfoVO.getProjectId();
            SportsProject sportsProject = getSportsProjectByUser(user.getId(), personalInfoVO.getRoleType());
            if (projectId.equals(sportsProject.getId())) {
                if (CommonConstant.PROJECT_STEP_FINISH.equals(sportsProject.getProjectStep())) {
                    return Result.error("案例已提交，不允许修改，如有需要请联系管理员处理！");
                }
                log.info("案例ID不为空，说明个人用户信息已经存在，需要修改，projectId={}", personalInfoVO.getProjectId());
                int i = updatePersonInfo(personalInfoVO.getProjectId(), username);
                addPersonInfo(personalInfoVO, projectId, user);
                if (i == 0) {
                    return Result.error("保存数据失败，请联系管理员查看原因！");
                }
            } else {
                log.info("当前用户的案例={}，传入的案例={}", sportsProject.getId(), projectId);
                return Result.error("当前案例与已存在的案例不匹配，请联系管理员查看原因！");
            }
        } else {
            //新增案例主表
            String id = IdWorker.getIdStr();
            projectId = ProjectCodeUtils.getProjectCode(id.substring(id.length() - 4, id.length()));
            addSportsProject(user, projectId, personalInfoVO.getRoleType(), personalInfoVO.getPersonalInfo().getName());
            addPersonInfo(personalInfoVO, projectId, user);
        }
        map.put("projectId", projectId);
        return Result.OK("新增成功!", map);
    }

    @Transactional
    public void addPersonInfo(PersonalInfoVO personalInfoVO, String projectId, SysUser user){
        log.info("新增个人填报信息生成案例Id==={}", projectId);
        String username = user.getUsername();
        // 3-1.将个人信息写入
        addPersonalInfo(username,personalInfoVO.getPersonalInfo(), projectId);
        // 3-2.新增荣誉证书URL
        List<OssFileVO> honorOssIds = personalInfoVO.getHonorOssIds();
        if (null != honorOssIds && honorOssIds.size() > 0) {
//            for (int i = 0; i < honorOssIds.size(); i++) {
//                sportsProjectFileService.addOssFile(honorOssIds.get(i).getOssFileId(), projectId, username, CommonConstant.OSS_FILE_TYPE_HONOR, null);
                //改成批量上传
//            }
            sportsProjectFileService.batchOssFile(honorOssIds, projectId, username, CommonConstant.OSS_FILE_TYPE_HONOR);
        }
        // 3-3.新增职称证书URL
        List<OssFileVO> professionalOssIds = personalInfoVO.getProfessionalOssIds();
        if (null != professionalOssIds && professionalOssIds.size() > 0) {
//            for (int i = 0; i < professionalOssIds.size(); i++) {
//                sportsProjectFileService.addOssFile(professionalOssIds.get(i).getOssFileId(), projectId, username, CommonConstant.OSS_FILE_TYPE_PROFESSIONAL, null);
//            }
            //改成批量上传
            sportsProjectFileService.batchOssFile(professionalOssIds, projectId, username, CommonConstant.OSS_FILE_TYPE_PROFESSIONAL);
        }
        // 3-4.代表性成果URL
        List<OssFileVO> resultCoverOssIds = personalInfoVO.getResultCoverOssIds();
        if (null != resultCoverOssIds && resultCoverOssIds.size() > 0) {
//            for (int i = 0; i < resultCoverOssIds.size(); i++) {
//                sportsProjectFileService.addOssFile(resultCoverOssIds.get(i).getOssFileId(), projectId, username, CommonConstant.OSS_FILE_TYPE_RESULT, null);
//            }
            sportsProjectFileService.batchOssFile(resultCoverOssIds, projectId, username, CommonConstant.OSS_FILE_TYPE_RESULT);
        }

        //4.将个人教育信息写入
        if (null != personalInfoVO.getPersonalEduList() && personalInfoVO.getPersonalEduList().size() > 0) {
            batchInsertPersonalEdu(username, personalInfoVO.getPersonalEduList(), projectId);
        }
        //5.将个人经历信息写入
        if (null != personalInfoVO.getPersonalWorkExperienceList() && personalInfoVO.getPersonalWorkExperienceList().size() > 0) {
            batchInsertPersonalWorkExperience(username, personalInfoVO.getPersonalWorkExperienceList(), projectId);
        }
    }

    /**
     * 给案例ID对应的个人信息数据打删除标识
     * @param projectId
     * @param username
     */
    @Transactional
    public int updatePersonInfo(String projectId, String username){
        try {
            //给个人用户信息打删除标识
            SportsPersonalInfo sportsPersonalInfo = sportsPersonalInfoMapper.selectByProjectId(projectId);
            //加密信息
//            //姓名
//            if (null != sportsPersonalInfo.getName() && !"".equals(sportsPersonalInfo.getName())) {
//                sportsPersonalInfo.setName(SensitiveInfoUtil.getEncodeData(sportsPersonalInfo.getName(), SensitiveEnum.ENCODE));
//            }
//            //地址
//            if (null != sportsPersonalInfo.getAddress() && !"".equals(sportsPersonalInfo.getAddress())) {
//                sportsPersonalInfo.setAddress(SensitiveInfoUtil.getEncodeData(sportsPersonalInfo.getAddress(), SensitiveEnum.ENCODE));
//            }
//            //身份证号
//            if (null != sportsPersonalInfo.getIdNumber() && !"".equals(sportsPersonalInfo.getIdNumber())) {
//                sportsPersonalInfo.setIdNumber(SensitiveInfoUtil.getEncodeData(sportsPersonalInfo.getIdNumber(), SensitiveEnum.ENCODE));
//            }
//            //手机号
//            if (null != sportsPersonalInfo.getPhone() && !"".equals(sportsPersonalInfo.getPhone())) {
//                sportsPersonalInfo.setPhone(SensitiveInfoUtil.getEncodeData(sportsPersonalInfo.getPhone(), SensitiveEnum.ENCODE));
//            }
//
//            //邮箱
//            if (null != sportsPersonalInfo.getEmail() && !"".equals(sportsPersonalInfo.getEmail())) {
//                sportsPersonalInfo.setEmail(SensitiveInfoUtil.getEncodeData(sportsPersonalInfo.getEmail(), SensitiveEnum.ENCODE));
//            }
            sportsPersonalInfo.setIzActive(CommonConstant.COMMON_STATUS_Y);
            sportsPersonalInfo.setUpdateBy(username);
            sportsPersonalInfo.setUpdateTime(new Date());
            sportsPersonalInfoMapper.updateById(sportsPersonalInfo);

            //给个人用户信息的教育信息打删除标识
            List<SportsPersonalEdu> sportsPersonalEdus = getPersonalEduByProjectId(projectId);
            if (null != sportsPersonalEdus && !sportsPersonalEdus.isEmpty()) {
                sportsPersonalEdus.forEach(x -> {
                    x.setUpdateTime(new Date());
                    x.setUpdateBy(username);
                    x.setIzActive(CommonConstant.COMMON_STATUS_Y);
                    sportsPersonalEduMapper.updateById(x);
                });
            }

            //给个人用户信息的经历信息打删除标识
            List<SportsPersonalWorkExperience> sportsPersonalWorkExperiences = getPersonalWorkExpByProjectId(projectId);
            if (null != sportsPersonalWorkExperiences && sportsPersonalWorkExperiences.size() > 0) {
                sportsPersonalWorkExperiences.forEach(x -> {
                    x.setUpdateTime(new Date());
                    x.setUpdateBy(username);
                    x.setIzActive(CommonConstant.COMMON_STATUS_Y);
                    sportsPersonalWorkExperienceMapper.updateById(x);
                });
            }

            //给个人用户信息的荣誉证书信息打删除标识
            List<SportsProjectFile> sportsProjectHonorFiles = sportsProjectFileService.getFileList(projectId, CommonConstant.OSS_FILE_TYPE_HONOR);
            sportsProjectFileService.updateFileList(sportsProjectHonorFiles, username);

            //给个人用户信息的职称证书信息打删除标识
            List<SportsProjectFile> sportsProjectProfessionalFiles = sportsProjectFileService.getFileList(projectId, CommonConstant.OSS_FILE_TYPE_PROFESSIONAL);
            sportsProjectFileService.updateFileList(sportsProjectProfessionalFiles, username);

            //给个人用户信息的职称证书信息打删除标识
            List<SportsProjectFile> sportsProjectResultFiles = sportsProjectFileService.getFileList(projectId, CommonConstant.OSS_FILE_TYPE_RESULT);
            sportsProjectFileService.updateFileList(sportsProjectResultFiles, username);
            return 1;
        } catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }




    @Override
    @Transactional
    public Result<?> updatePersonalInfo(PersonalInfoVO personalInfoVO, String username) {
        //判断案例状态是否能修改
        SportsProject sportsProject = sportsProjectMapper.selectById(personalInfoVO.getPersonalInfo().getProjectId());
        if (CommonConstant.PROJECT_STEP_FINISH.equals(sportsProject.getProjectStep())){
            return Result.error("案例已提交不能修改！");
        }

        //查找案例ID
        String projectId = personalInfoVO.getPersonalInfo().getProjectId();
        //更新个人信息
        SportsPersonalInfo sportsPersonalInfo = sportsPersonalInfoMapper.selectByProjectId(projectId);
        if (null != sportsPersonalInfo) {
            sportsPersonalInfo = personalInfoVO.getPersonalInfo();
            sportsPersonalInfo.setUpdateBy(username);
            sportsPersonalInfo.setUpdateTime(new Date());
            sportsPersonalInfoMapper.updateById(sportsPersonalInfo);
        }

        //更新或新增荣誉证书
        List<OssFileVO> professionalOssIds = personalInfoVO.getProfessionalOssIds();
        if (null != professionalOssIds && professionalOssIds.size() > 0){
            professionalOssIds.forEach(x -> {
                sportsProjectFileService.updateOssId(x.getOssFileId(), projectId, username, CommonConstant.OSS_FILE_TYPE_PROFESSIONAL);
            });
        }

        //更新或新增职称证书
        List<OssFileVO> honorOssIds = personalInfoVO.getHonorOssIds();
        if (null != honorOssIds && honorOssIds.size() > 0){
            honorOssIds.forEach(x -> {
                sportsProjectFileService.updateOssId(x.getOssFileId(), projectId, username, CommonConstant.OSS_FILE_TYPE_HONOR);
            });
        }

        //更新个人教育信息
        List<SportsPersonalEdu> personalEdus = personalInfoVO.getPersonalEduList();
        if (null != personalEdus && personalEdus.size() > 0) {
            personalEdus.forEach(x -> {
                updateOrInsertPersonalEdu(x, username, projectId);
            });
        }

        //更新个人经历信息
        List<SportsPersonalWorkExperience> workExperiences = personalInfoVO.getPersonalWorkExperienceList();
        if (null != workExperiences && workExperiences.size() > 0){
            workExperiences.forEach(x -> {
                updateOrInsertPersonalWorkExp(x, username, projectId);
            });
        }
        return Result.OK("更新成功！");
    }

    @Override
    public Result<PublicInfoVO> getPublicInfo(String username, String roleType) {
        SysUser sysUser = sysUserMapper.getUserByName(username);
        PublicInfoVO publicInfoVO = new PublicInfoVO();
        publicInfoVO.setPhone(sysUser.getPhone());
        publicInfoVO.setName(sysUser.getRealname());
        publicInfoVO.setBirthday(sysUser.getBirthday());
        publicInfoVO.setSex(sysUser.getSex());
        publicInfoVO.setEmail(sysUser.getEmail());
        publicInfoVO.setIdNumber(sysUser.getIdNumber());
        publicInfoVO.setNation(sysUser.getNation());
//        String userId = sysUser.getId();
        /*SportsProject sportsProject = getSportsProjectByUser(userId, roleType);
        PublicInfoVO publicInfoVO = new PublicInfoVO();
        if (null != sportsProject) {
            SportsPersonalInfo sportsPersonalInfo = sportsPersonalInfoMapper.selectByProjectId(sportsProject.getId());
            String name = sportsPersonalInfo.getName();
            String email = sportsPersonalInfo.getEmail();
            String phone = sportsPersonalInfo.getPhone();
            String idNumber = sportsPersonalInfo.getIdNumber();
            if (null != sportsPersonalInfo) {
//                publicInfoVO.setProjectId(sportsProject.getId());
                publicInfoVO.setNation(sportsPersonalInfo.getNation());
                publicInfoVO.setSex(sportsPersonalInfo.getSex());
                publicInfoVO.setBirthday(sportsPersonalInfo.getBirthday());
                if (sportsProject.getYear() >= 2025) {
                    if (CommonConstant.PROJECT_STEP_FINISH.equals(sportsProject.getProjectStep())) {
                        publicInfoVO.setName(SensitiveInfoUtil.getDecodeData(name));
                        publicInfoVO.setIdNumber(SensitiveInfoUtil.getDecodeData(idNumber));
                        publicInfoVO.setPhone(SensitiveInfoUtil.getDecodeData(phone));
                        publicInfoVO.setEmail(SensitiveInfoUtil.getDecodeData(email));
                    } else {
                        publicInfoVO.setEmail(email);
                        publicInfoVO.setName(name);
                        publicInfoVO.setIdNumber(idNumber);
                        publicInfoVO.setPhone(phone);
                    }
                } else {
                    publicInfoVO.setEmail(email);
                    publicInfoVO.setName(name);
                    publicInfoVO.setIdNumber(idNumber);
                    publicInfoVO.setPhone(phone);
                }
            }
        } else {
            publicInfoVO.setPhone(sysUser.getPhone());
        }*/
        return Result.OK("获取公共信息成功！", publicInfoVO);
    }

    public SysUserVerifyLog checkVerify(CheckInfoVO checkInfoVO){
        LambdaQueryWrapper<SysUserVerifyLog> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserVerifyLog::getIzActive, CommonConstant.COMMON_STATUS_N);
        lambdaQueryWrapper.eq(SysUserVerifyLog::getUsername, checkInfoVO.getName());
        lambdaQueryWrapper.eq(SysUserVerifyLog::getIdNumber, checkInfoVO.getIdNumber());
        lambdaQueryWrapper.eq(SysUserVerifyLog::getPhone, checkInfoVO.getPhone());
        return sysUserVerifyLogMapper.selectOne(lambdaQueryWrapper);
    }

    @Override
    public Result<?> checkPhoneAndIdNumber(CheckInfoVO checkInfoVO) {
        String message = "";

        //判断身份证号是否存在redis中，如果存在直接返回
        String redisKey = CommonConstant.VERIFY_IDNUMBER_PHONE_NAME_KEY + checkInfoVO.getIdNumber();
        if (redisUtil.get(redisKey) != null) {
            return Result.OK("success");
        }
        //从数据库中查找数据，如果三要素在数据库中存在，则直接跳出不调收费接口
        SysUserVerifyLog sysUserVerifyLog = checkVerify(checkInfoVO);
        if (null == sysUserVerifyLog) {
            sysUserVerifyLog = new SysUserVerifyLog();
            sysUserVerifyLog.setUsername(checkInfoVO.getName());
            sysUserVerifyLog.setIdNumber(checkInfoVO.getIdNumber());
            sysUserVerifyLog.setIzActive(CommonConstant.COMMON_STATUS_N);
            sysUserVerifyLog.setPhone(checkInfoVO.getPhone());
            sysUserVerifyLog.setCreateBy(checkInfoVO.getPhone());
            sysUserVerifyLog.setCreateTime(new Date());
            sysUserVerifyLog.setCheckStatus(CommonConstant.DEL_FLAG_1);
            String host = "https://kzmobilev2.market.alicloudapi.com";
            String path = "/api/mobile_three/check";
            String method = "POST";
            String appcode = "9933f39c28aa42dd9d6af21720b245a8";
            Map<String, String> headers = new HashMap<String, String>();
            //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
            headers.put("Authorization", "APPCODE " + appcode);
            //根据API的要求，定义相对应的Content-Type
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            Map<String, String> querys = new HashMap<String, String>();
            Map<String, String> bodys = new HashMap<String, String>();
            bodys.put("mobile", checkInfoVO.getPhone());
            bodys.put("name", checkInfoVO.getName());
            bodys.put("idcard", checkInfoVO.getIdNumber());
            try {
                /**
                 * 重要提示如下:
                 * HttpUtils请从
                 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
                 * 下载
                 *
                 * 相应的依赖请参照
                 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
                 */
                HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
                if (response == null) {
                    return Result.error("认证失败！");
                }
                //获取response的body
                String responseBody = EntityUtils.toString(response.getEntity());
                log.info("responseBody==={}" + responseBody);
                JSONObject object = JSON.parseObject(responseBody);
                if (null != object && (Integer) object.get("code") == 200) {
                    JSONObject data = JSONObject.parseObject(object.get("data").toString());
                    if (data.get("result").equals("0")) {
                        message = "success";
                        //成功数据写入redis
                        redisUtil.set(redisKey, bodys);
                        //写入用户校验表中
                        sysUserVerifyLog.setCheckStatus(CommonConstant.DEL_FLAG_0);
                        sysUserVerifyLogMapper.insert(sysUserVerifyLog);
                    } else {
                        log.info("error desc==={}" + data.get("desc").toString());
                        log.info("======");
                        sysUserVerifyLogMapper.insert(sysUserVerifyLog);
                        return Result.error("姓名+手机号+身份证号三要素不一致，请核对信息后正确填写！");
                    }
                } else {
                    log.info("error msg ==={}" + object.get("msg").toString());
                    sysUserVerifyLogMapper.insert(sysUserVerifyLog);
                    return Result.error("姓名+手机号+身份证号三要素不一致，请核对信息后正确填写！");
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.info("exception === {}", e.getMessage());
            }
            return Result.OK(message);
        } else {
            if (sysUserVerifyLog.getCheckStatus() == CommonConstant.DEL_FLAG_1) { //调过收费接口，并且数据不一致
                return Result.error("姓名+手机号+身份证号三要素不一致，请核对信息后正确填写！");
            } else {
                return Result.OK("success");
            }
        }
    }

    public SportsProject getSportsProjectByUser(String userId, String roleType){
        Calendar calendar = Calendar.getInstance();
        //1.获取当前用户填写过的所有案例
        LambdaQueryWrapper<SportsProject> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SportsProject::getIzActive, CommonConstant.COMMON_STATUS_N);
        lambdaQueryWrapper.eq(SportsProject::getUserId, userId);
//        lambdaQueryWrapper.eq(SportsProject::getYear, calendar.get(Calendar.YEAR));
        if (null != roleType && !"".equals(roleType)){
            lambdaQueryWrapper.eq(SportsProject::getRoleType, roleType);
        }
        lambdaQueryWrapper.orderByDesc(SportsProject::getCreateTime);
        List<SportsProject> list = sportsProjectMapper.selectList(lambdaQueryWrapper);
        if (null != list && list.size() > 0){
            return list.get(0);
        }
        return null;
    }


    /**
     * 判断当前工作经验ID是否存在，如存在则更新，否则新增
     * @param sportsPersonalWorkExperience
     * @param username
     * @param projectId
     */
    public void updateOrInsertPersonalWorkExp(SportsPersonalWorkExperience sportsPersonalWorkExperience, String username, String projectId) {
        if (null != sportsPersonalWorkExperience.getId() && !"".equals(sportsPersonalWorkExperience.getId())){
            sportsPersonalWorkExperience.setUpdateBy(username);
            sportsPersonalWorkExperience.setUpdateTime(new Date());
            sportsPersonalWorkExperienceMapper.updateById(sportsPersonalWorkExperience);
        } else {
            sportsPersonalWorkExperience.setCreateBy(username);
            sportsPersonalWorkExperience.setCreateTime(new Date());
            sportsPersonalWorkExperience.setProjectId(projectId);
            sportsPersonalWorkExperienceMapper.insert(sportsPersonalWorkExperience);
        }
    }


    /**
     * 判断当前个人教育ID是否存在，如存在则更新，否则新增
     * @param personalEdu
     * @param username
     * @param projectId
     */
    public void updateOrInsertPersonalEdu(@NotNull SportsPersonalEdu personalEdu, String username, String projectId){
        if (null != personalEdu.getId() && !"".equals(personalEdu.getId())){
            personalEdu.setUpdateBy(username);
            personalEdu.setUpdateTime(new Date());
            sportsPersonalEduMapper.updateById(personalEdu);
        } else {
            personalEdu.setCreateBy(username);
            personalEdu.setCreateTime(new Date());
            personalEdu.setProjectId(projectId);
            sportsPersonalEduMapper.insert(personalEdu);
        }
    }

    public List<SportsPersonalEdu> getPersonalEduByProjectId(String projectId){
        LambdaQueryWrapper<SportsPersonalEdu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SportsPersonalEdu::getProjectId, projectId);
        queryWrapper.eq(SportsPersonalEdu::getIzActive, "0");
        List<SportsPersonalEdu> personalEdus = sportsPersonalEduMapper.selectList(queryWrapper);
        return personalEdus;
    }

    /**
     * 新增项目主表数据
     * @param user
     * @param projectId
     * @param roleType
     */
    public void addSportsProject(SysUser user, String projectId, String roleType, String name){
        Calendar calendar = Calendar.getInstance();
        SportsProject sportsProject = new SportsProject();
        sportsProject.setId(projectId);
        sportsProject.setProjectStep(CommonConstant.PROJECT_STEP_PERSONAL_INFO);
        sportsProject.setProjectStatus(CommonConstant.PROJECT_STATUS_PENDING);
        sportsProject.setRoleId(CommonConstant.ROLE_TYPE_APPLICANT);
        sportsProject.setUserId(user.getId());
        sportsProject.setRoleType(roleType);
        sportsProject.setCreateBy(user.getUsername());
        sportsProject.setUserName(name);
        sportsProject.setCreateTime(new Date());
        sportsProject.setYear(calendar.get(Calendar.YEAR));
        sportsProjectMapper.insert(sportsProject);
    }

    public List<SportsPersonalWorkExperience> getPersonalWorkExpByProjectId(String projectId) {
        LambdaQueryWrapper<SportsPersonalWorkExperience> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SportsPersonalWorkExperience::getProjectId, projectId);
        queryWrapper.eq(SportsPersonalWorkExperience::getIzActive, "0");
        return sportsPersonalWorkExperienceMapper.selectList(queryWrapper);
    }

    /**
     * 新增个人基本信息  并进行加密处理
     * @param personalInfo
     * @param projectId
     * @param username
     */
    @Transactional
    public void addPersonalInfo(String username, SportsPersonalInfo personalInfo, String projectId){
        //将个人信息中的用户信息更新至用户主表
        SysUser sysUser = sysUserMapper.getUserByName(username);
        if (null != sysUser) {
            sysUser.setSex(personalInfo.getSex());
            sysUser.setIdNumber(personalInfo.getIdNumber());
            sysUser.setNation(personalInfo.getNation());
            sysUser.setPhone(personalInfo.getPhone());
            sysUser.setEmail(personalInfo.getEmail());
            if (null != personalInfo.getAddress() && !"".equals(personalInfo.getAddress())) {
                sysUser.setAddress(personalInfo.getAddress());
            }
            if (null != personalInfo.getSchoolAddress() && !"".equals(personalInfo.getSchoolAddress())){
                sysUser.setAddress(personalInfo.getSchoolAddress());
            }
            sysUser.setRealname(personalInfo.getName());
            sysUserMapper.updateById(sysUser);
        }
        personalInfo.setProjectId(projectId);
        personalInfo.setCreateBy(username);
        personalInfo.setCreateTime(new Date());
        sportsPersonalInfoMapper.insert(personalInfo);
    }

    /**
     * 批量新增个人教育信息
     * @param personalEdus
     * @param projectId
     * @param username
     */
    public void batchInsertPersonalEdu(String username, List<SportsPersonalEdu> personalEdus, String projectId){
        personalEdus.stream().forEach(x->{
            x.setCreateBy(username);
            x.setCreateTime(new Date());
            x.setProjectId(projectId);
            sportsPersonalEduMapper.insert(x);
        });
    }

    /**
     * 批量新增个人工作经历
     * @param workExperiences
     * @param projectId
     */
    public void batchInsertPersonalWorkExperience(String userId, List<SportsPersonalWorkExperience> workExperiences, String projectId){
        workExperiences.stream().forEach(x->{
            x.setCreateBy(userId);
            x.setCreateTime(new Date());
            x.setProjectId(projectId);
            x.setProjectId(projectId);
            sportsPersonalWorkExperienceMapper.insert(x);
        });
    }


    public static void main(String[] args) {
        String host = "https://kzmobilev2.market.alicloudapi.com";
        String path = "/api/mobile_three/check";
        String method = "POST";
        String appcode = "9933f39c28aa42dd9d6af21720b245a8";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("mobile", "18116990112");
        bodys.put("name", "韩秀龙");
        bodys.put("idcard", "652901198809308013");
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            //获取response的body
            System.out.println("==========" + EntityUtils.toString(response.getEntity()));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
